<?php
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

/**
 * 返回数据验证不通过的响应信息
 *
 * @param string $message
 * @return \Illuminate\Http\JsonResponse
 */
function invalidation($message)
{
    return response()->json(['message' => $message], 422);
}

/**
 * 无访问权限时，返回的响应信息
 *
 * @param $message
 * @return \Illuminate\Http\JsonResponse
 */
function access_denied($message = '无访问权限')
{
    return response()->json(['message' => $message], 403);
}

/**
 * 获取单页查询个数，并限制最大值
 *
 * @param int $max
 * @return int
 */
function per_page($max = 50)
{
    $perPage = intval(app()->request->get('per_page'));
    if ($perPage <= 0) {
        return 10;
    }

    return min($perPage, $max);
}

/**
 * 定义restful路由
 *
 */
function route_resource($uri, $controller)
{
    Route::get($uri, $controller . '@index');
    Route::get($uri . '/create', $controller . '@create');
    Route::post($uri, $controller . '@store');
    Route::get($uri . '/{id}', $controller . '@show');
    Route::get($uri . '/{id}/edit', $controller . '@edit');
    Route::put($uri . '/{id}', $controller . '@update');
    Route::patch($uri . '/{id}', $controller . '@update');
    Route::delete($uri . '/{id}', $controller . '@destroy');
}

/**
 * 根据时间划分文件存放的相对路径
 *
 * @param string $type 名称单词
 * @return string
 */
function upload_path($type)
{
    return str_plural($type) . '/' . date('Ym') . '/' . date('d');
}

/**
 * 上传图片
 *
 * @param string $key
 * @param string $type 图片类型，不同类型存放于不同的目录，默认为 image
 * @param int $height 以 height 为最大高度，等比例缩小图片；为0时，不缩放
 * @return false|string
 */
function upload_image($key, $type = 'image', $height = 0)
{
    $file = app()->request->file($key);
    $path = $file->storeAs(upload_path($type), random_filename($file));

    // 等比例缩小
    if ($height > 0) {
        $filePath = Storage::path($path);
        image_shrink($filePath, $height);
    }

    return $path;
}

/**
 * 以 height 为最大高度，等比例缩小图片
 *
 * @param string $filePath 图片路径
 * @param int $height 默认最大高度为 200
 */
function image_shrink($filePath, $height = 200)
{
    // 等比例缩小
    Image::make($filePath)->heighten($height, function ($constraint) {
        $constraint->upsize();
    })->save();
}

function is_image($file)
{
    $file = new File($file);
    return in_array($file->guessExtension(), ['jpeg', 'png', 'gif', 'bmp', 'svg']);
}

function image_url($path)
{
    if (empty($path) || 0 === strpos($path, 'http')) {
        return $path;
    }
    return Storage::url($path);
}

/**
 * 获取随机生成的文件名（10位随机数）
 *
 * @param mixed $param 文件扩展名，如果参数为`\Illuminate\Http\UploadedFile`对象，通过getExtension获取
 * @return string
 */
function random_filename($param = null)
{
    if ($param instanceof \Illuminate\Http\UploadedFile) {
        $extension = $param->extension();
    } else {
        $extension = (string) $param;
    }

    $name = str_random(10);
    return $extension ? "$name.$extension" : $name;
}

// 获取服务器地址
function get_server_addr()
{
    $serverHost = env('SERVER_HOST', '127.0.0.1');
    $serverPort = env('SERVER_PORT', 9501);
    return $serverHost . ':' . $serverPort;
}

/**
 * 获取对象相应的属性，类似 array_only
 *
 * @param stdClass $object
 * @param array $keys
 * @return array
 */
function object_only($object, $keys)
{
    $data = [];

    foreach ($keys as $key) {
        $data[$key] = $object->{$key};
    }

    return $data;
}
